package com.beviswong.themedemo

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class ThemeActivity : AppCompatActivity() {
    private lateinit var btnDefault: View
    private lateinit var btnDark: View
    private lateinit var btnLight: View

    override fun onCreate(savedInstanceState: Bundle?) {
        // 必须在setContentView前应用主题
        applyTheme()
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_theme)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initViews()
    }

    private fun initViews() {
        btnDefault = findViewById(R.id.btn_default)
        btnDark = findViewById(R.id.btn_dark)
        btnLight = findViewById(R.id.btn_light)

        btnDefault.setOnClickListener { switchTheme(ThemeManager.THEME_DEFAULT) }
        btnDark.setOnClickListener { switchTheme(ThemeManager.THEME_DARK) }
        btnLight.setOnClickListener { switchTheme(ThemeManager.THEME_LIGHT) }

        findViewById<TextView>(R.id.tv_title).setBackgroundColor(
            getThemeColor(R.attr.themePrimaryButtonBackground)
        )
    }

    /** 应用保存的主题 */
    private fun applyTheme() {
        val themeType = ThemeManager.getSavedTheme(this)
        setTheme(ThemeManager.getThemeStyle(themeType))
    }

    /** 切换主题并重启Activity生效 */
    private fun switchTheme(themeType: Int) {
        ThemeManager.saveTheme(this, themeType)
        finish()
        startActivity(intent)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            overrideActivityTransition(OVERRIDE_TRANSITION_OPEN, 0, 0)
        } else {
            overridePendingTransition(0, 0)
        }
    }

    /** 获取主题资源ID（主题的属性值是资源 ID 的情况下） */
    private fun getThemeResId(attributeResId: Int): Int {
        val typedValue = TypedValue()
        theme.resolveAttribute(attributeResId, typedValue, true)
        return typedValue.resourceId
    }

    /** 获取主题中配置颜色值（主题的属性值是颜色值的情况下） */
    private fun getThemeColor(attributeResId: Int): Int {
        val typedValue = TypedValue()
        theme.resolveAttribute(attributeResId, typedValue, true)
        return typedValue.data
    }

    companion object {
        fun start(mainActivity: MainActivity) {
            mainActivity.startActivity(Intent(mainActivity, ThemeActivity::class.java))
        }
    }
}